package org.dormi.learn;

import java.util.concurrent.*;

/**
 * Future适用于把计算剥离在一个单独的线程环境中处理，然后期待它“未来”返回一个结果给你
 *
 * @author : dormi330
 * @since : 22/04/18
 */
public class FutureDemo02 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("hello future");
                Thread.sleep(3000);
                //模拟计算错误
                int i = 10 / 0;
                return 1;
            }
        };
        Future<Integer> future = executorService.submit(callable);

        System.out.println("...其他操作...");
        while (!future.isDone()) {
            try {
                Integer count = future.get(2, TimeUnit.SECONDS);
                System.out.println("count: " + count);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();            // int i = 10 / 0 throw 的异常从这里出来
            } catch (TimeoutException e) {
                e.printStackTrace();            // 如果 sleep2 则发生超时异常
            }
        }
        executorService.shutdown();
    }

}
